//
//  HMOAuthModel.swift
//  HMSlender
//
//  Created by 赵少朋赵少朋 on 17/1/24.
//  Copyright © 2017年 ITheima. All rights reserved.
//

import UIKit

class HMOAuthModel: NSObject {

    let documentPath = (NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archiver")
    
    static let shared:HMOAuthModel = HMOAuthModel()
    
    var userAccountModel:HMOAuthControllerModel?
    //单例只创建一次 通过一个属性保存沙盒的数据 然后直接使用属性
    override init() {
        super.init()
        //目的让沙盒数据只请求一次
        userAccountModel = getUserModel()
    }
    
    //请求access_token
    var access_token: String? {
    
        if let user = userAccountModel?.access_token {
            
            if userAccountModel?.expires_Date?.compare(Date()) == ComparisonResult.orderedDescending {
                return user
            } else {
                return nil
            }
        } else {
            return nil
        }
    }
    
    var isLogin: Bool {
    
        return access_token != nil
    }
    
    

}



extension HMOAuthModel {
    
    func getUserAccount(code:String, isFinish:@escaping (Bool)->()) -> Void {
        
        NetworkTools.sharedNetworkTools.loadUserAccount(code: code, success: {(response)->() in
            //获取授权接口数据
            //返回access_token等数据
            
            if let r = response as? [String:Any] {
                
                let responseModel = HMOAuthControllerModel.yy_model(withJSON: r)
                
                self.getUserInfo(userOAuthModel: responseModel!,isFinish: isFinish)
            }
            isFinish(false)
//            return 写还是不写
        }, failure: {(error)->() in
            
            isFinish(false)
            print("失败",error!)
        })
        
    }
    
    
    func getUserInfo(userOAuthModel:HMOAuthControllerModel, isFinish:@escaping (Bool)->()) -> Void {
        
        
        NetworkTools.sharedNetworkTools.loadUserInfo(userOAuthModel: userOAuthModel, success: {(response)->() in
            
            //判断结果是否有值 并且是字典
            guard let res = response as? [String:Any] else {
                isFinish(false)
                return
            }
            
            userOAuthModel.screen_name = res["screen_name"] as? String
            userOAuthModel.avatar_large = res["avatar_large"] as? String
            //用户数据请求成功
            self.saveUserModel(userModel: userOAuthModel)
            
            isFinish(true)
        }, failure: {(error)->() in
            isFinish(false)
            print("失败",error!)
        })
        
    }
}

extension HMOAuthModel {

    ///保存模型
    func saveUserModel(userModel:HMOAuthControllerModel) {
        
        //赋值 后 第一次启动后沙盒里依然会在调用之前有数据
        self.userAccountModel = userModel
        //保存模型
        NSKeyedArchiver.archiveRootObject(userModel, toFile: documentPath)

    }
    
    ///获取模型
    func getUserModel() -> HMOAuthControllerModel? {

        let userAccountModel = NSKeyedUnarchiver.unarchiveObject(withFile: documentPath) as? HMOAuthControllerModel
        
        return userAccountModel
    }
}

